package org.insidesource.flexbugs.dao.impl;

import java.util.List;

import org.insidesource.flexbugs.dao.RestaurantDao;
import org.insidesource.flexbugs.model.Restaurant;
import org.springframework.orm.jpa.support.JpaDaoSupport;

public class RestaurantDaoJpaImpl extends JpaDaoSupport implements RestaurantDao
{
	public void delete(Restaurant restaurant)
	{
		this.getJpaTemplate().remove(restaurant);
	}

	@SuppressWarnings("unchecked")
	public List<Restaurant> findByEntreeNameLike(String entreeName)
	{
//		return this.getJpaTemplate().find("select r from Restaurant r where r.entrees.name like ?1", entreeName);
		return this.getJpaTemplate().find("select distinct r from Restaurant r inner join r.entrees e where e.name like ?1", entreeName);
	}

	public Restaurant findById(long id)
	{
		return this.getJpaTemplate().find(Restaurant.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Restaurant> findByName(String name)
	{
		return this.getJpaTemplate().find("select r from Restaurant r where r.name=?1", name);
	}

	@SuppressWarnings("unchecked")
	public List<Restaurant> findByStreetName(String streetName)
	{
		return this.getJpaTemplate().find("select r from Restaurant r where r.address.streetName=?1", streetName);
	}

	@SuppressWarnings("unchecked")
	public List<Restaurant> findRestaurantsWithVegetarianEntrees()
	{
//		return this.getJpaTemplate().find("select r from Restaurant r where r.entrees.vegetarian = 'true'");
		return this.getJpaTemplate().find("select distinct r from Restaurant r inner join r.entrees e where e.vegetarian='true'");
	}

	public void save(Restaurant restaurant)
	{
		this.getJpaTemplate().persist(restaurant);
	}

	public Restaurant update(Restaurant restaurant)
	{
		return this.getJpaTemplate().merge(restaurant);
	}

}
